import { createFetch } from '@vueuse/core'
import { ElMessage } from 'element-plus'

interface CommonResult<T> {
  msg: string
  code: number
}

export const useRequest = createFetch({
  baseUrl: "http://127.0.0.1:8092",
  options: {
    beforeFetch({options}) {      
      return {
        options
      }
    },
    async afterFetch(ctx) {
        const data = await ctx.response.json()
        if(data.code !== '2000') {
            ElMessage.error(data.msg)
            return data
        }
        return data
    },
  },
  fetchOptions:{
    mode: "cors",//这里设置为no-cors会影响请求头content-type设置不生效，必须设置modef否则服务器开启跨域也会跨域,
    credentials: "include"
  }
})
// 想要自定义content-type 需要在post方法传第二个type参数如post(JSON.stringify(data),"application/json")。这种情况必须要手动stringify; post(data)这样就会自动转json并且content-type自动json
export const usePostWithJson = <T>(url: string, data: any) => useRequest<T>(url).post(data)